import vue from "@vitejs/plugin-vue";
import { UserConfig, ConfigEnv, loadEnv, defineConfig } from "vite";

/* 组件的自动引入 */
import AutoImport from "unplugin-auto-import/vite";

import Components from 'unplugin-vue-components/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';

import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";

import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

import vueJsx from "@vitejs/plugin-vue-jsx";

import UnoCSS from "unocss/vite";

import { resolve } from "path";

const pathSrc = resolve(__dirname, "src");
// https://cn.vitejs.dev/config
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd());
  return {
    resolve: {
      alias: {
        "@": pathSrc,
      },
    },
    css: {
      // CSS 预处理器
      preprocessorOptions: {
        // 定义全局 SCSS 变量
        scss: {
          javascriptEnabled: true,
          additionalData: `
            @use "@/assets/styles/common-xy.scss" as *;
          `,
        },
      },
    },
    server: {
      port: Number(env.VITE_APP_PORT),
      open: true,
      // proxy: {
      //   /* 反向代理 */
      //   [env.VITE_APP_BASE_API]: {
      //     changeOrigin: true,
      //     target: env.VITE_APP_API_URL,
      //     rewrite: (path) =>
      //       path.replace(new RegExp("^" + env.VITE_APP_BASE_API), ""),
      //   },
      // },
    },
    plugins: [
      vue(),
      vueJsx(),
      UnoCSS({
        hmrTopLevelAwait: false,
      }),
      // 自动导入：https://github.com/sxzz/element-plus-best-practices/blob/main/vite.config.ts
      AutoImport({
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ["vue", "@vueuse/core", "vue-router", "pinia"],
        resolvers: [AntDesignVueResolver(), IconsResolver({})],
        eslintrc: {
          enabled: false,
          filepath: "./.eslintrc-auto-import.json",
          globalsPropValue: true,
        },
        vueTemplate: true,
        dts: 'src/types/auto-imports.d.ts',
      }),
      Components({
        /* 组件自动按需引入 */
        resolvers: [
          // 自动导入 Element Plus 组件
          AntDesignVueResolver({
            importStyle: false
          }),
          // 自动注册图标组件
          IconsResolver({ enabledCollections: ["ant-design"] }),
        ],
        // 指定自定义组件位置(默认: src/components)
        dirs: ["src/components", "src/**/components"],
        dts: 'src/types/components.d.ts',
      }),
      Icons({
        autoInstall: true,
        compiler: "vue3"
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [resolve(pathSrc, "assets/icons")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
    ],
    /* 预加载项目必需的组件 */
    optimizeDeps: {
      include: [
        "vue",
        "vue-router",
        "pinia",
        "axios",
        "element-plus",
        "@vueuse/core",
      ],
    },
    // 构建配置
    build: {
      sourcemap: false, // 不生成sourcemap
      outDir: env.VITE_APP_OUTDIR,
      chunkSizeWarningLimit: 2000,
      minify: "terser",
      terserOptions: {
        compress: {
          keep_infinity: true, // 防止 Infinity 被压缩成 1/0，这可能会导致 Chrome 上的性能问题
          drop_console: true,
          drop_debugger: true,
        },
        format: {
          comments: false, // 删除注释
        },
      },
      rollupOptions: {
        output: {
          // manualChunks: {
          //   "vue-i18n": ["vue-i18n"],
          // },
          // 用于从入口点创建的块的打包输出格式[name]表示文件名,[hash]表示该文件内容hash值
          entryFileNames: "js/[name].[hash].js",
          // 用于命名代码拆分时创建的共享块的输出命名
          chunkFileNames: "js/[name].[hash].js",
          /**
           * 用于输出静态资源的命名，[ext]表示文件扩展名
           * @param assetInfo 
           * @returns 
           */
          assetFileNames: (assetInfo: any) => {
            const info = assetInfo.name.split(".");
            let extType = info[info.length - 1];
            if (
              /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)
            ) {
              extType = "media";
            } else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(assetInfo.name)) {
              extType = "img";
            } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
              extType = "fonts";
            }
            return `${extType}/[name].[hash].[ext]`;
          },
        },
      },
    },
  };
});
